package com.qwt.part_time_api.config.interceptor;


import com.qwt.part_time_api.pojo.Role;
import com.qwt.part_time_api.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;


/**
 * 获取当前访问的url所需要的角色权限
 *
 * @author 君子慎独
 */

@Component
@Slf4j
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        log.info("获取当前访问的url所需要的角色权限");
        //获取请求地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        //用户、角色、资源方案：查询具体某个接口的权限
        List<Role> roleList = roleService.findAllByApiUrl(requestUrl);

        if (roleList == null || roleList.size() == 0) {
            log.info("可以任意访问");
            //请求路径没有配置权限，表明该请求接口可以任意访问
            return null;
        }

        String[] attributes = new String[roleList.size()];
        for (int i = 0; i < roleList.size(); i++) {
            attributes[i] = roleList.get(i).getName();
        }
        return SecurityConfig.createList(attributes);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 改为true,否则注入时报错
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}


